﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ThaireInvestmentWeb.Util
{
    public class IntegerModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            //return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue);
            //// of course replace with your custom conversion logic


            object result = null;

            // Don't do this here!
            // It might do bindingContext.ModelState.AddModelError
            // and there is no RemoveModelError!
            // 
            // result = base.BindModel(controllerContext, bindingContext);

            string modelName = bindingContext.ModelName;
        

            // Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
            // Both "." and "," should be accepted, but aren't.
            //string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            //string alternateSeperator = (wantedSeperator == "," ? "." : ",");

            //if (attemptedValue.IndexOf(wantedSeperator) == -1
            //    && attemptedValue.IndexOf(alternateSeperator) != -1)
            //{
            //    attemptedValue =
            //        attemptedValue.Replace(alternateSeperator, wantedSeperator);
            //}
           
            try
            {
                string attemptedValue =  null;
                ValueProviderResult value = bindingContext.ValueProvider.GetValue(modelName);
                if(value!=null)
                    attemptedValue = value.AttemptedValue;
                if (bindingContext.ModelMetadata.IsNullableValueType
                    && string.IsNullOrWhiteSpace(attemptedValue))
                {
                    return null;
                }
                attemptedValue = attemptedValue.Replace(",", "");
                result = int.Parse(attemptedValue);
            }
            catch (FormatException e)
            {
                bindingContext.ModelState.AddModelError(modelName, e);
            }

            return result;
        }
    }
}